package com.cjzuji.rental.dao.impl;

import com.cjzuji.rental.dao.RenRZuOrderDao;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class RenRZuOrderDaoImpl implements RenRZuOrderDao {
    @Autowired
    OrderMapper orderMapper;

    private static final Logger logger = LoggerFactory.getLogger(RenRZuOrderDaoImpl.class);
    @Override
    @Transactional
    public long save(Map<String, Object> item,Map<String, Object> data,Map<String,Object> amountlist,String userName,String userPhone,String userIdcard) {
        //logger.info("item {}",item);
        Map<String, Object> ordersuk = (Map<String, Object>) item.get("spu_info");  //手机情况
        Map<String, Object> depositInfo = (Map<String, Object>) item.get("deposit_info"); //押金情况
        //logger.info("spu_info {}",ordersuk);
        String brank = " ";
        String color = " ";
        String suk = " ";
        if (ordersuk != null && ordersuk.size() > 0){
            brank = ordersuk.get("spu_name").toString();
            String spec = ordersuk.get("sku_name").toString();
            String[] parts = spec.split(" ");
            for (String part : parts){
                if (part.contains("色") || part.contains("黑") || part.contains("红") || part.contains("白") || part.contains("灰") || part.contains("蓝") || part.contains("青")) {
                    color = part;
                } else if (part.contains("G")||part.contains("T")) {
                    suk = part;
                }
            }
        }
        Map<String, Object> ordertime =(Map<String, Object>) data.get("tenancy_data");
        int idCardStatus = 0;
        if (!userIdcard.equals("")) {
            idCardStatus = 1;
        }
        int orderStatus;
        String deliveryNo = "";
        switch (data.get("order_status").toString()) {
            case "2":
                orderStatus = 1;  //待发货
                deliveryNo = data.get("logistic_number").toString();
                break;
            case "4":   //订单状态   3租用中
                orderStatus = 3;
                deliveryNo = data.get("logistic_number").toString();
                break;
            case "5":
                orderStatus = 3;
                deliveryNo = data.get("logistic_number").toString();
                break;
            case "33":
                orderStatus = 3;
                deliveryNo = data.get("logistic_number").toString();
                break;
            case "20":    //订单状态   5已完成
                orderStatus = 5;
                deliveryNo = data.get("logistic_number").toString();
                break;
            default:
                orderStatus = 7;
                break;
        }
        Map<String, Object> buyoutAmountinfo = (Map<String, Object>) item.get("order_pay_info");
        logger.info("order_pay_info {}",buyoutAmountinfo);
        Double buyoutAmount = 0.0;
        if (buyoutAmountinfo.get("current_purchase_price") != "" || buyoutAmountinfo.get("buy_out_price") != "" || buyoutAmountinfo.get("grads_buyout_price") != ""){
            if (buyoutAmountinfo.get("current_purchase_price") != ""){
                buyoutAmount = Double.parseDouble(buyoutAmountinfo.get("current_purchase_price").toString());
            }else {
                //获取买断价
                String orderId = data.get("order_id").toString();
                List<Map<String, Object>> buyoutAmountlist;
                buyoutAmountlist = getBuyoutAmountDetail(orderId);
                if (buyoutAmountlist == null){
                    buyoutAmount = Double.parseDouble(buyoutAmountinfo.get("buy_out_price").toString());
                }else {
                    buyoutAmount = Double.valueOf(buyoutAmountlist.get(buyoutAmountlist.size()-1).get("current_purchase_price").toString());
                }
            }
        }
        String monthRepayment = amountlist.get("intsallment_price").toString();
        Double monthRepayment1 = 0.0;
        if(!monthRepayment.isEmpty()){
            monthRepayment1 = Double.parseDouble(monthRepayment);
        }
        int Term = Integer.parseInt(amountlist.get("installment_time").toString());
        if (amountlist.get("first_rent") != ""){
            Term = Term + 1;
        }
        if (amountlist.get("last_rent") != ""){
            Term = Term + 1;
        }
        Orders renRZuOrder = Orders.builder()
                .shopId(2)
                .platformId(3)
                .orderId(data.get("order_id").toString())
                .realName(userName)    //下单用户
                .phone(userPhone)   //下单用户手机号
                .opinion(" ")  //风控
                //.assigner(assigner)  //分配人 备注人
                .orderIdTag(data.get("user_id").toString()) //平台订单ID
                .carBrand(brank) //产品备注
                .colour(color)  //商品属性
                .sku(suk)  //商品SKU
                .actualFiancingAmount(Double.parseDouble(amountlist.get("rental_need_pay").toString()))  //总租金  rental_need_pay
                .buyoutAmount(buyoutAmount)  //买断价
                .discountAmount(Double.parseDouble(amountlist.get("rental_money").toString())-Double.parseDouble(amountlist.get("rental_need_pay").toString()))
                .monthRepayment(monthRepayment1) //月租金
                .bondFreeCreditAmt(Double.parseDouble(amountlist.get("rental_need_pay").toString())+buyoutAmount) //订单总金额
                .surplusBondAmt(Double.parseDouble(depositInfo.get("had_pay_deposit").toString())) //押金
                .leaseTerm(String.valueOf(Term))   //订单租期  检查
                .idAuthStatus(idCardStatus)  //身份证上传状态
                .rentStartTime(ordertime.get("start_time").toString())  //租赁开始时间
                .rentLastTime(ordertime.get("end_time").toString())  //租赁结束时间
                .status(orderStatus)    //订单状态
                .deliveryNo(deliveryNo)  //快递单号
                .createTime(data.get("created_at").toString())  // 下单时间
                .updateTime(new Date())
                .screenRisksAmount(0.0) //碎屏金额   真实支付的碎屏价格
                //.screenRisksType(screenRisksType)//碎屏状态
                .build();
        try {
            orderMapper.insert(renRZuOrder);
            return renRZuOrder.getId();
        }catch (Exception e){

            logger.info("添加错误" + e.getMessage());
            throw e; // 重新抛出，确保事务回滚
        }
    }
    public List<Map<String, Object>> getBuyoutAmountDetail(String orderId) {
        logger.info("获取买断价详情");
        String url = "https://admin.rrzu.com/super/protocol-platform-center/get-grads-buyout?order_id=" + orderId;
        String cookie = "_c_WBKFRo=FSIWmp9izQJrxo4RIt2V7e3jK9UHfmlN8lecEHmR; aliyungf_tc=e63c28916cc805999b37f13f8e77c0c4c0eaec5877541b7d52d9032921691b69; canary-route=\"f84c3e119efe43b9\"; Remember-Me=1; _identity=c4fa157addc50e3035c4911fddb3c8a02d550b378c52dbadf5fdbce8fc4e8939a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22_identity%22%3Bi%3A1%3Bs%3A54%3A%22%5B%2261277616%22%2C%22rvQjLxeW_vH2mM6INBxNdmqhukoiq6eB%22%2C259617%5D%22%3B%7D; shuzhiSecret=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwYy5tZXJjaGFudCIsInN1YiI6IjYxMjc3NjE2IiwiYXVkIjpbInBjLm1lcmNoYW50Il0sImV4cCI6MTc2MDc1ODMxNSwibmJmIjoxNzYwNDk5MTE1LCJpYXQiOjE3NjA0OTkxMTUsImp0aSI6IjIxMjU0NTkzNTM0MjY5MjY2OTc2Mjc5NjI4MzY3NjM5IiwiSWQiOjYxMjc3NjE2LCJVc2VybmFtZSI6IuaftOaXpeaZtCIsIlBob25lIjoiMTQ3OTYzMjg5MzEiLCJJc0FkbWluIjpmYWxzZSwiUm9sZSI6InNlcnZlclN0YWZmIiwiU2VydmVySWQiOjIzMTc0LCJUZXJtaW5hbCI6IiJ9.h6aasfFA0X6mGNI2sFygFyNsu6fXEqT9AbJS3SJ5Vdg; Go-Token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOjYxMjc3NjE2LCJleHAiOjE3NjA3NTgzMTUsImlhdCI6MTc2MDQ5OTExNSwic2NlbmUiOjUsInNlcnZlcl9pZCI6MjMxNzQsInVzZXJfaWQiOjYxMjc3NjE2fQ.M1zSwxFCBDmr2oXvhb86is3vBNmG7Pehn9KgiS9zevQ; Data-Token=2f0e6d2f773388f5; _csrf=3170071681566556ffdcc60a0cb209e083f0f8a1d4486b96940be3e2268327b1a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22fHS2zL72TcGD545z_G_f1dqPC8zBxI5Q%22%3B%7D; workOrderSixhour=1; illegalWorkOrderSixhour=1; RRZUJI_SE=pd52l3vu9i3j5kftvlta61lsrp; acw_tc=b6db6557-1e1e-40a2-9ed1-4db8ecee136de9d1f44910227c23beb2129a1a7ef803";
        String outBuyDetail = Tool.getRequest(url,"","", "", cookie);
        logger.info("买断价详情 {}",outBuyDetail);
        ObjectMapper outBuyDetailMapper = new ObjectMapper();
        Map<String, Object> outBuyDetailMap = null;
        try {
            outBuyDetailMap = outBuyDetailMapper.readValue(outBuyDetail, Map.class);
        } catch (JsonProcessingException e) {
            logger.info("解析买断价详情错误 {}",e.getMessage());
            throw new RuntimeException(e);
        }
        Map<String, Object> outBuyData = (Map<String, Object>) outBuyDetailMap.get("data");
        if (outBuyData.containsKey("buyout_list")){
            List<Map<String, Object>> outBuyList = (List<Map<String, Object>>) outBuyData.get("buyout_list");
            return outBuyList;
        }
        return null;
    }
}
